package com.example.customview.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import com.sample.base.utils.dp
import kotlin.math.cos
import kotlin.math.sin

class PieView(context: Context?, attrs: AttributeSet?) : View(context, attrs) {
    companion object {
        private val PIE_VIEW_RADIUS = 150f.dp
        private val PIE_VIEW_ANGLES = floatArrayOf(
           55f, 90f, 55f, 160f
        )
        private val PIE_VIEW_COLORS = listOf(
            Color.parseColor("#f03752"),
            Color.parseColor("#03DAC5"),
            Color.parseColor("#f86b1d"),
            Color.parseColor("#6200EE")
        )

        private val OFFSET_LENGTH = 12f.dp

    }

    private val paint = Paint(Paint.ANTI_ALIAS_FLAG)

    override fun onDraw(canvas: Canvas) {
        var startAngle = 0f
        var offsetIndex = 3
        for ((index, angle) in PIE_VIEW_ANGLES.withIndex()) {
            paint.color = PIE_VIEW_COLORS[index]

            if (index == offsetIndex) {
                canvas.save()
                val dx = OFFSET_LENGTH * cos(Math.toRadians(startAngle + angle / 2f.toDouble()))
                val dy = OFFSET_LENGTH * sin(Math.toRadians(startAngle + angle / 2f.toDouble()))
                canvas.translate(
                    dx.toFloat(), dy.toFloat()
                )
            }

            canvas.drawArc(
                width / 2f - PIE_VIEW_RADIUS, height / 2f - PIE_VIEW_RADIUS,
                width / 2f + PIE_VIEW_RADIUS, height / 2f + PIE_VIEW_RADIUS,
                startAngle, angle, true, paint
            )
            startAngle += angle

            if (index == offsetIndex) {
                canvas.restore()
            }
        }

    }

}